﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using System.Web;

namespace VotanetWebSite.Acceso_Votante
{
    public partial class Sufragio_Votante : System.Web.UI.Page
    {
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        private static Uri previousPage = null;
        public Voter GetVoter()
        {
            return Session["Voter"] as Voter;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                previousPage = HttpContext.Current.Request.UrlReferrer;

                if (previousPage != null)
                {
                    if (previousPage.AbsolutePath != "/Acceso_Votante/Sufragio_Votante.aspx")
                    {
                        Session["VotingID"] = Context.Items["Vota_Id"].ToString();
                    }
                }
                else
                {
                    Response.RedirectPermanent("../Login_Votante.aspx");
                }
            }

            string votingId = Session["VotingID"].ToString();

            if (GetVoter() != null && !string.IsNullOrWhiteSpace(votingId) && (previousPage.AbsolutePath == "/Home/Pagina_Inicio.aspx" || previousPage.AbsolutePath == "/Acceso_Votante/Sufragio_Votante.aspx"))
            {
                CreateCandidatePanel(votingId);
                lblNombreVotanteLogin.Text = GetVoter().GetFullName();
            }
            else
            {
                Response.RedirectPermanent("../Login_Votante.aspx");
            }


        }

        protected void CreateCandidatePanel(string votingId)
        {
            VotingLogic votingLogic = new VotingLogic();
            List<Candidate> candidateList = votingLogic.GetListCandidatesLogic(KEY, votingId);
            Voting voting = votingLogic.GetVotingByIdList(KEY, votingId);

            if (candidateList != null && voting != null)
            {

                lblEncabezado.Text = voting.name;
                var list = candidateList.GroupBy(x => x.office);

                Session["cant"] = list.Count();
                int cont = 1;
                foreach (IGrouping<string, Candidate> lc in list)
                {
                    PanelVotacion.Controls.Add(CreateTableByOffice(lc.Key, lc.ToList<Candidate>(), cont));
                    cont++;
                }
                PanelBotones.Controls.Add(CreateButtonPanel());
            }
            else
            {
                Response.RedirectPermanent("../Login_Votante.aspx");
            }
        }

        private Panel CreateTableByOffice(string office, List<Candidate> candidateList, int cont)
        {
            VoterLogic voterLogic = new VoterLogic();
            Panel panel = new Panel();
            panel.CssClass = "bordeRedondo";

            Panel encabezado = new Panel();
            encabezado.CssClass = "encabezado";
            encabezado.Controls.Add(CreateControl.OfTypeLabel("lblMenu" + office, "Cargo " + office, "label12"));
            panel.Controls.Add(encabezado);

            Table principalTable = new Table();
            TableRow pictureRow = new TableRow();
            TableRow labelRow = new TableRow();
            TableRow radioRow = new TableRow();

            int internalCont = 1;
            foreach (Candidate cc in candidateList)
            {
                pictureRow.Cells.Add(CreateCell.WithImagen("VoterPictures" + cont + internalCont, cc.pictureString, @"~/Images/CandidateImage/"));
                principalTable.Rows.Add(pictureRow);

                labelRow.Cells.Add(CreateCell.WithLabel("lblNombreVotante" + cont + internalCont, cc.GetFullName(), "label12"));
                principalTable.Rows.Add(labelRow);

                radioRow.Cells.Add(CreateCell.WithRadioList(cc.id, "GrupoRadio" + office));
                principalTable.Rows.Add(radioRow);

                internalCont++;
            }
            TableRow whiteRow = new TableRow();
            whiteRow.Cells.Add(CreateCell.WithImagen("ImagenVotoBlanco" + office, "VotoBlanco.jpg", @"~/Images/"));
            principalTable.Rows.Add(whiteRow);

            TableRow whiteLabelRow = new TableRow();
            whiteLabelRow.Cells.Add(CreateCell.WithLabel("lblVotoBlanco" + office, "Voto Blanco", "label12"));
            principalTable.Rows.Add(whiteLabelRow);

            TableRow whiteRadioRow = new TableRow();
            whiteRadioRow.Cells.Add(CreateCell.WithRadioList(voterLogic.EncryptDataLogic("Blanco" + office, KEY), "GrupoRadio" + office));
            principalTable.Rows.Add(whiteRadioRow);
            panel.Controls.Add(principalTable);

            return panel;
        }

        private Panel CreateButtonPanel()
        {
            Panel panelBotones = new Panel();
            panelBotones.Controls.Add(new TableCell());
            panelBotones.Controls.Add(new TableCell());
            panelBotones.Controls.Add(CreateButtonCell("BtnLimpiar", "Limpiar"));
            panelBotones.Controls.Add(new TableCell());
            panelBotones.Controls.Add(CreateButtonCell("BtnContinuar", "Continuar"));
            return panelBotones;

        }

        protected TableCell CreateButtonCell(string id, string text)
        {
            TableCell celda = new TableCell();
            Button sendButton = CreateControl.OfTypeButton(id, text);
            sendButton.CssClass = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only";
            sendButton.Click += new EventHandler(BotonEnviar_Click);
            celda.Controls.Add(sendButton);
            return celda;
        }

        protected Dictionary<string, string> ValidateVote()
        {
            Dictionary<string, string> response = new Dictionary<string, string>();
            foreach (Control c in Util.FindControlRecursive(Page).Where(x => x is RadioButton))
            {
                RadioButton radio = c as RadioButton;
                if (radio.Checked)
                {
                    response.Add(radio.GroupName, radio.ID);
                }
            }
            return response;
        }

        protected void CleanFormRecursive()
        {
            foreach (Control c in Util.FindControlRecursive(Page).Where(x => x is RadioButton))
            {
                RadioButton radio = c as RadioButton;
                radio.Checked = false;
            }
        }

        protected void BotonEnviar_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            switch (button.CommandArgument)
            {
                case "BtnContinuar":
                    Dictionary<string, string> response = ValidateVote();
                    int cant = Convert.ToInt32(Session["cant"]);
                    if (response.Count >= cant)
                    {
                        Context.Items.Add("Identificador", response);
                        Server.Transfer("Procesar_Voto.aspx");
                    }
                    else
                    {
                        Messages.Show(Page, "Seleccione " + cant + "  Opciones");
                    }
                    break;

                case "BtnLimpiar":
                    CleanFormRecursive();
                    break;
            }
        }

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }
    }
}